package com.sgb.capital.view.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.text.InputType;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.sgb.capital.R;
import com.sgb.capital.base.BaseActivity;
import com.sgb.capital.callback.Constants;
import com.sgb.capital.callback.ZMessageEvent;
import com.sgb.capital.databinding.EditpersonbankActivityBinding;
import com.sgb.capital.model.AddAndEditCardsBean;
import com.sgb.capital.model.BankBean;
import com.sgb.capital.model.BankEntity;
import com.sgb.capital.utils.CryptoUtils;
import com.sgb.capital.utils.Utils;
import com.sgb.capital.view.pop.CardsListPop;
import com.sgb.capital.view.pop.TipPop;
import com.sgb.capital.view.widget.MToast;
import com.sgb.capital.viewmodel.BankModel;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import razerdp.basepopup.BasePopupWindow;


/**
 * 作者:张磊
 * 日期:2021/5/12
 * 说明:编辑个人银行卡
 */
public class EditPersonBankActivity extends BaseActivity {

    private EditpersonbankActivityBinding mBinding;
    private BankModel mModel;
    private AddAndEditCardsBean addAndEditCardsBean = new AddAndEditCardsBean();
    private TipPop mSaveSuccessPop, mTipOpenPop, mErrorPop, mWithdrawPop;
    private int mProcess;
    private BankBean mBankBean;
    private CardsListPop mListPop;

    public static void start(Context context, String json) {
        Intent intent = new Intent(context, EditPersonBankActivity.class);
        intent.putExtra("data", json);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }

    @Override
    protected void initView() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        Utils.setStatusBarLightMode(this, true);
        mBinding = DataBindingUtil.setContentView(this, R.layout.editpersonbank_activity);
        mModel = new ViewModelProvider(this).get(BankModel.class);
        mBinding.itemTvCarNum.setInputType(InputType.TYPE_CLASS_NUMBER);
        mBinding.itemTvCarPhone.setInputType(InputType.TYPE_CLASS_NUMBER);

        mSaveSuccessPop = new TipPop(mContext, "温馨提示", "恭喜您，修改银行卡信息成功", null, "知道了");
        mSaveSuccessPop.setOnDismissListener(new BasePopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                Utils.sendMsg(Constants.EVENT_REFRESH, null);
                finish();
            }
        });
        mListPop = new CardsListPop(this);
        mTipOpenPop = new TipPop(this, "温馨提示", "开通个人钱包后可使用此功能", "前往开通", "知道了");
        mErrorPop = new TipPop(this, "温馨提示", "当前银行不支持设置为提现卡", null, "知道了");
        mWithdrawPop = new TipPop(this, "温馨提示", "设置为提现卡后，该卡不可修改", "确定", "取消");
    }


    @Override
    public void initData() {
        String data = getIntent().getStringExtra("data");
        mBankBean = new Gson().fromJson(data, BankBean.class);
        String idCard = CryptoUtils.decryptAES_ECB(mBankBean.idCard);
        String bankCard = CryptoUtils.decryptAES_ECB(mBankBean.bankCard);
        String phone = CryptoUtils.decryptAES_ECB(mBankBean.phone);
        mBankBean.bankCard = bankCard;
        mBankBean.phone = phone;
        mBankBean.idCard = idCard;
        // 解密
        mBinding.itemTvAccountName.setHint(mBankBean.accountName);
        mBinding.itemTvIdNumber.setHint(idCard.substring(0, 4) + "********" + idCard.substring(idCard.length() - 4));
        mBinding.itemTvBankName.setContent(mBankBean.openingBank);
        mBinding.itemTvCarNum.setText(bankCard);
        mBinding.itemTvCarPhone.setContent(phone);
        mBinding.itemTvBankName.setContent(mBankBean.bankName);
        mModel.getProcess(this);
    }


    /***
     * 支付银行卡数据验证
     */
    private void checkPayData() {
        if (TextUtils.isEmpty(mBinding.itemTvBankName.getContent())) {
            MToast.showLongToast(this, mBinding.itemTvBankName.getHint());
            return;
        } else if (TextUtils.isEmpty(mBinding.itemTvCarNum.getText().toString())) {
            MToast.showLongToast(this, mBinding.itemTvCarNum.getHint().toString());
            return;
        } else if (mBinding.itemTvCarNum.getText().toString().length() < 8) {
            MToast.showToast(this, "银行卡号格式错误");
            return;
        } else if (TextUtils.isEmpty(mBinding.itemTvCarPhone.getContent())) {
            MToast.showLongToast(this, mBinding.itemTvCarPhone.getHint());
            return;
        } else if (!Utils.isChinaPhoneLegal(mBinding.itemTvCarPhone.getContent())) {
            MToast.showToast(this, "手机号格式错误");
            return;
        }

        // TODO: 2021/6/16 0016 加密
        System.out.println("数据信息=="+ new Gson().toJson(mBankBean));
        mBankBean.idCard = CryptoUtils.encryptAES_ECB(mBankBean.idCard);
        mBankBean.phone = CryptoUtils.encryptAES_ECB(mBinding.itemTvCarPhone.getContent());
        mBankBean.openingBank = mBinding.itemTvBankName.getContent();
        mBankBean.bankCard = CryptoUtils.encryptAES_ECB(mBinding.itemTvCarNum.getText().toString().trim());
        System.out.println("保存加密=="+ new Gson().toJson(mBankBean));
        mModel.saveBankCard(this, mBankBean);
    }

    public void initListener() {
        mBinding.ivBack.setOnClickListener(v -> finish());
        mSaveSuccessPop.setOnDismissListener(new BasePopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                Utils.sendMsg(Constants.EVENT_REFRESH, null);
                finish();
            }
        });
        mBinding.saveView.setOnClickListener(v -> checkPayData());
        mTipOpenPop.mTvSure.setOnClickListener(v -> {
            mTipOpenPop.dismiss();
            OpenAccountFirstActivity.start(mContext, false);
        });
        mBinding.tvSetWithdrawalView.setOnClickListener(v -> {
            if (mProcess == 0) {
                mTipOpenPop.show();
                return;
            }
            mModel.hasToBindBank(this, mBankBean.id);
        });
        mBinding.itemTvBankName.setOnWholeItemClickListener(v -> {
            if (mListPop.mDatas.size() == 0) {
                mModel.getQpBank(this);
            } else {
                mListPop.show();
            }
        });
        // // TODO: 2021/5/20 0020 设置提现银行卡
        mWithdrawPop.mTvSure.setOnClickListener(v -> {
            if (TextUtils.isEmpty(mBinding.itemTvBankName.getContent())) {
                MToast.showLongToast(this, mBinding.itemTvBankName.getHint());
                return;
            } else if (TextUtils.isEmpty(mBinding.itemTvCarNum.getText().toString())) {
                MToast.showLongToast(this, mBinding.itemTvCarNum.getHint().toString());
                return;
            } else if (mBinding.itemTvCarNum.getText().toString().length() < 8) {
                MToast.showToast(this, "银行卡号格式错误");
                return;
            } else if (TextUtils.isEmpty(mBinding.itemTvCarPhone.getContent())) {
                MToast.showLongToast(this, mBinding.itemTvCarPhone.getHint());
                return;
            } else if (!Utils.isChinaPhoneLegal(mBinding.itemTvCarPhone.getContent())) {
                MToast.showToast(this, "手机号格式错误");
                return;
            }
            mWithdrawPop.dismiss();
            mBankBean.phone = mBinding.itemTvCarPhone.getContent();
            mBankBean.bankCard = mBinding.itemTvCarNum.getText().toString();
            mBankBean.bankName = mBinding.itemTvBankName.getContent();
            SetWithdrawBackActivity.start(this, new Gson().toJson(mBankBean));
        });
        // 个人开户
        mTipOpenPop.mTvSure.setOnClickListener(v -> {
            mTipOpenPop.dismiss();
            OpenAccountFirstActivity.start(this, false);
        });

    }

    @Override
    public void initObserve() {

        // 获取银行卡列表
        mModel.mBank.observe(this, bankEntities -> {
            if (bankEntities != null && bankEntities.size() != 0) {
                for (int i = 0; i < bankEntities.size(); i++) {
                    if (bankEntities.get(i).name.contains(mBinding.itemTvBankName.getContent())) {
                        bankEntities.get(i).isSelect = true;
                        mListPop.mLastIndex = i;
                        continue;
                    }
                }
                mListPop.mDatas = bankEntities;
                mListPop.show();
            }
        });
        mModel.mIsWithdraw.observe(this, s -> {
            if (s.contains("1")) {
                mWithdrawPop.show();
            } else {
                mErrorPop.show();
            }
        });
        mModel.mBaseEntity.observe(this, baseEntity -> {
            if (baseEntity != null) {
                mSaveSuccessPop.show();
            }
        });
        mModel.mCapitalEntity.observe(this, capitalEntity -> mProcess = capitalEntity.process);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    @Subscribe
    public void getCode(ZMessageEvent event) {
        switch (event.code) {
            case Constants
                    .EVENT_HIDE:
                Utils.sendMsg(Constants.EVENT_REFRESH, null);
                finish();
                break;
            case Constants
                    .EVENT_SELECT:
                BankEntity data = (BankEntity) event.data;
                mBinding.itemTvBankName.setContent(data.name);
                break;
        }
    }

}